//
//  MenuNextViewController.m
//  Food
//
//  Created by dlios on 15-7-15.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "MenuNextViewController.h"
#import "BaseHeader.h"
#import "MenuTableViewCell.h"
#import "MenuSearchPage_Class.h"
#import "CollocationTableViewCell.h"

#import "AppropriateDetailController.h"
#import "MakeController.h"
#import "AppropriteObject.h"

#import "MJRefresh.h"
#import "MBProgressHUD.h"

@interface MenuNextViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain) UITableView *menuTableView;
@property (nonatomic, retain) NSMutableArray *menuArr;
@property (nonatomic, retain) UIScrollView *mainScrollView;
@property (nonatomic, retain) UISegmentedControl *segment;

@property (nonatomic, retain) UITableView *appropriateTableView;
@property (nonatomic, retain) NSMutableArray *appropriateArr;
@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UILabel *label1;

@property (nonatomic, retain) UIViewController *appropriateController;
@property (nonatomic, assign) NSInteger rowNumber;

@property (nonatomic, retain) MBProgressHUD *HUD;
@property (nonatomic, retain) NSMutableArray *footerArr;
@property (nonatomic, assign) NSInteger page;

@end

@implementation MenuNextViewController

- (void)dealloc
{
    [_appropriateController release];
    [_footerArr release];
    [_HUD release];
    
    [_label1 release];
    [_label release];
    [_appropriateArr release];
    [_appropriateTableView release];
    
    [_menuArr release];
    [_mainScrollView release];
    [_menuTableView release];
    [_segment release];
    
    [_sName release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.menuArr = [NSMutableArray array];
    self.appropriateArr = [NSMutableArray array];
    self.footerArr = [NSMutableArray array];
    
    //主mainScrollView
    self.mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Width, Height - 40)];
    self.mainScrollView.delegate = self;
    self.mainScrollView.pagingEnabled = YES;
    self.mainScrollView.showsHorizontalScrollIndicator = YES;
    self.mainScrollView.contentSize = CGSizeMake(Width * 2, 0);
    [self.view addSubview:self.mainScrollView];
    self.mainScrollView.contentOffset = CGPointMake(0, 0);
    [_mainScrollView release];
    
    //菜谱的menuTableView
    self.menuTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 0, Width - 20, Height - 64 - 44 - 5)];
    self.menuTableView.delegate = self;
    self.menuTableView.dataSource = self;
    self.menuTableView.showsVerticalScrollIndicator = NO;
    [self.mainScrollView addSubview:self.menuTableView];
    
    //注册
    [self.menuTableView registerClass:[MenuTableViewCell class] forCellReuseIdentifier:@"menu"];
    [_menuTableView release];
    
    //菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.removeFromSuperViewOnHide = YES;
    self.HUD.labelText = @"稍等";
    self.HUD.detailsLabelText = @"正在加载中";
    self.HUD.square = YES;
    [self.view addSubview:self.HUD];
    self.HUD.mode = MBProgressHUDModeIndeterminate;

    
    //相克/宜搭的
    self.appropriateTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 0, Width - 20, 150)];
    self.appropriateTableView.delegate = self;
    self.appropriateTableView.dataSource = self;
    [self.mainScrollView addSubview:self.appropriateTableView];
    //注册
    [self.appropriateTableView registerClass:[CollocationTableViewCell class] forCellReuseIdentifier:@"appropriate"];
    [_appropriateTableView release];
    
    //lable食材相克表
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(10, self.appropriateTableView.frame.origin.y + self.appropriateTableView.frame.size.height, Width, 50)];
    self.label.text = @"食材相宜/相克:";
    [_label release];

    //button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake((Width - 100) / 2, self.label.frame.origin.y + 50, 100, 35);
    button.backgroundColor = [UIColor lightGrayColor];
    button.layer.cornerRadius = 12;
    [button setTitle:@"详细列表" forState:UIControlStateNormal];
    button.tintColor = [UIColor whiteColor];
    button.showsTouchWhenHighlighted = YES;
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.appropriateController = [[UIViewController alloc] init];
    self.appropriateController.view.frame = CGRectMake(Width, 0, Width, Height);
    [self.mainScrollView addSubview:self.appropriateController.view];
    //把数据加到Controller
    [self.appropriateController.view addSubview:self.appropriateTableView];
    [self.appropriateController.view addSubview:self.label];
    [self.appropriateController.view addSubview:button];
    
    [_appropriateController release];
    
    [self datahander];
    [self segmentControl];
    [self setUpRefresh];

}

//下拉刷新, 上拉加载
- (void)setUpRefresh
{
    //刷新
    [self.menuTableView addHeaderWithTarget:self action:@selector(myHeaderRefresh)];
    //加载
    [self.menuTableView addFooterWithTarget:self action:@selector(myFooterRefresh)];
    //一进入程序自动刷新
    [self.menuTableView headerBeginRefreshing];
    
    //刷新
    self.menuTableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.menuTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.menuTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    //加载
    self.menuTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.menuTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.menuTableView.footerRefreshingText = @"正在帮你加载中,不客气";
    
}

//刷新方法
- (void)myHeaderRefresh
{
    [self.menuArr removeAllObjects];
    [AFNet connectNetGetDataWithURLString:[NSString stringWithFormat:@"http://api.xiangha.com/so5/getSoData/?s=%@&type=caipu&page=1", self.sName] parameters:nil finishblock:^(id result) {
        
        //result是字典/数组
        NSMutableDictionary *temperDic = [result objectForKey:@"data"];
        self.menuArr = [MenuSearchPage_Class ClassArrayWithDictionaryArray:[temperDic objectForKey:@"dishs"]];
        
    }];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.menuTableView reloadData];
        [self.menuTableView headerEndRefreshing];
    });
    self.page = 2;
}

//加载方法
- (void)myFooterRefresh
{
    [self.footerArr removeAllObjects];
    [AFNet connectNetGetDataWithURLString:[NSString stringWithFormat:@"http://api.xiangha.com/so5/getSoData/?s=%@&type=caipu&page=%ld", self.sName, self.page++] parameters:nil finishblock:^(id result) {
        
        //result是字典/数组
        NSMutableDictionary *temperDic = [result objectForKey:@"data"];
        self.footerArr = [MenuSearchPage_Class ClassArrayWithDictionaryArray:[temperDic objectForKey:@"dishs"]];
        [self.menuArr addObjectsFromArray:self.footerArr];

    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.menuTableView reloadData];
        [self.menuTableView footerEndRefreshing];
    });
}

//mainScrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.mainScrollView) {
        NSInteger number = (scrollView.contentOffset.x + Width / 2) / Width;
        self.segment.selectedSegmentIndex = number;
    }
}

//segment
- (void)segmentControl
{
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"美食", @"相克/宜搭"]];
    self.segment.tintColor = [UIColor redColor];
    self.segment.selectedSegmentIndex = 0;
    self.navigationItem.titleView = self.segment;
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [_segment release];
   
}

//segment点击方法
- (void)segmentAction:(UISegmentedControl *)segment
{
    NSInteger number = segment.selectedSegmentIndex;
    if (0 == segment.selectedSegmentIndex) {
        [self.mainScrollView setContentOffset:CGPointMake(Width * number, 0) animated:YES];
    }else if (1 == segment.selectedSegmentIndex) {
        [self.mainScrollView setContentOffset:CGPointMake(Width * number, 0) animated:YES];
    }
    
}

//button点击方法
- (void)buttonAction:(UIButton *)button
{
    AppropriateDetailController *detail = [[AppropriateDetailController alloc] init];
    //写传值
    if (self.appropriateArr.count != 0) {
        
        detail.menuClass = [self.appropriateArr objectAtIndex:self.rowNumber];
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];

    } 

}

//tableView协议的两个必须实现的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.menuTableView) {
        return self.menuArr.count;
    }else {
        return self.appropriateArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.menuTableView]) {
        MenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"menu"];
        if (self.menuArr.count != 0) {
            //给cell赋值
            MenuSearchPage_Class *menu = [self.menuArr objectAtIndex:indexPath.row];
            cell.menuClass = menu;

        }
        return cell;
    }
    else {
        CollocationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"appropriate"];
        if (self.appropriateArr.count != 0) {
            //给cell赋值
            MenuSearchPage_Class *appropriate = [self.appropriateArr objectAtIndex:indexPath.row];
            cell.collocationClass = appropriate;
        }
        self.rowNumber = indexPath.row;
        return cell;
    }
    
    
}
//cell宽度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.menuTableView) {
        return 100;
    }
    else {
        return 50;
    }
}

//数据处理
- (void)datahander
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败! 请检查网络吧" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
        [self.HUD hide:YES];
    }

    else {
        [AFNet connectNetGetDataWithURLString:[NSString stringWithFormat:@"http://api.xiangha.com/so5/getSoData/?s=%@&type=caipu&page=1", self.sName] parameters:nil finishblock:^(id result) {
            
            
            [self.HUD show:YES];
            //result是字典/数组
            NSMutableDictionary *temperDic = [result objectForKey:@"data"];
        self.menuArr = [MenuSearchPage_Class ClassArrayWithDictionaryArray:[temperDic objectForKey:@"dishs"]];
        
        [self.menuTableView reloadData];
        [self.HUD hide:YES];
            if (self.menuArr.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有数据哦! 换个其他美食吧" delegate:self cancelButtonTitle:@"好" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
        
    }];
    [AFNet connectNetGetDataWithURLString:[NSString stringWithFormat:@"http://api.xiangha.com/so5/getSoData/?type=xiangke&s=%@&page=1", self.sName] parameters:nil finishblock:^(id result) {
        //result是字典/数组
        NSMutableArray *temerArr = [[result objectForKey:@"data"] objectForKey:@"taboo"];
        self.appropriateArr = [MenuSearchPage_Class ClassArrayWithDictionaryArray:temerArr];
        if (self.appropriateArr.count == 0) {
            self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Width, Height)];
            self.label1.backgroundColor = [UIColor whiteColor];
            self.label1.text = @"    没有您要找的数据哦~~~~~~😢";

            self.label1.userInteractionEnabled = NO;

            self.label1.textColor = [UIColor lightGrayColor];
            [self.appropriateController.view addSubview:self.label1];
            [_label1 release];
            
        }
        [self.appropriateTableView reloadData];
        
    }];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //写制作详情
    if (tableView == self.menuTableView) {
        MakeController *makeDetail = [[MakeController alloc] init];
        
        if (self.menuArr.count != 0) {
            
            //写传值的Id...................
            makeDetail.Code = [[self.menuArr objectAtIndex:indexPath.row] codeId];
            
        }
        
        [self.navigationController pushViewController:makeDetail animated:YES];
        [makeDetail release];

    }else {
        if (self.appropriateArr != 0) {
            AppropriateDetailController *appropriate = [[AppropriateDetailController alloc] init];
            appropriate.menuClass = [self.appropriateArr objectAtIndex:self.rowNumber];
            
            [self.navigationController pushViewController:appropriate animated:YES];
            [appropriate release];

        } else {
            self.appropriateTableView.allowsSelection = NO;
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
